// pages/index/newAED/newAED.js
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;

const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgpaths: [], //图片的临时地址
    imgUrls: [], //图片的云存储地址
    longitude: 113.324520,
    latitude: 23.099994,
    showflag: 'none',
    checkflag: false,
    citysIndex: [0, 0, 0], //给一个初始值索引，因为有三列，所以3个0
    region: ['省', '市', '区',''],
  },
  //上传图片
  chuantupian() {
    var that = this;
    wx.chooseImage({
      success: chooseResult => {
        that.setData({
          imgpaths: chooseResult.tempFilePaths
        })
      },
    })
  },
  bindRegionChange: function (e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  //定位到当前位置
  getPosition(e) {
    var that = this;
    if (that.data.checkflag == false) {
      that.setData({
        checkflag: true,
        showflag: 'block'
      })
      wx.getLocation({
        type: "gcj02",
        success: function(res) {
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            markers: [{
              latitude: res.latitude,
              longitude: res.longitude
            }]
          })
          //根据获取到的经纬度信息获取地理信息
          //需要用到腾讯位置服务SDK
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: that.data.latitude,
              longitude: that.data.longitude
            },
            success: function (res) {
              console.log(res);
              let province = res.result.ad_info.province
              let city = res.result.ad_info.city
              let district = res.result.address_component.district
              let address=res.result.address_component.street_number
              //console.log(province);
              that.setData({
                region:[province,city,district,address],
              })
      
            },
            fail: function (res) {
              console.log(res);
            },
            complete: function (res) {
              // console.log(res);
            }
          });
        }
      })
    } else {
      this.setData({
        checkflag: false,
        showflag: 'none'
      })
    }

  },
  uploadimg: function(path, count) {
    var that=this;
    var i=count;
    wx.cloud.uploadFile({
      // 指定上传到的云路径
      cloudPath: path + i + '.png', //以png格式存储，多张照片时名字最后一个数字为辨识
      // 指定要上传的文件的小程序临时文件路径
      filePath: that.data.imgpaths[i],
      // 成功回调
      success: res => {
        that.data.imgUrls[i] = res.fileID;
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == that.data.imgpaths.length) { //当图片传完时，停止调用       
          that.uploadInfo();
        } else { //若图片还没有传完，则继续调用函数
          that.uploadimg(path,i);
        }
      }
    })
  },
  uploadInfo(){
    //照片保存完毕，上传其它信息
    var that = this;
    var location = that.data.region[0] + "-" + that.data.region[1] + "-" + that.data.region[2];
    console.log(location);
    //得到的信息导入到数据库中
    db.collection('AEDlocation').add({
      data: {
        location:location,
        address: that.data.formInfo.detail.value.position,
        phone: that.data.formInfo.detail.value.phone,
        detail: that.data.formInfo.detail.value.detail_location,
        uploaddate: new Date(),
        longitude: that.data.longitude,
        latitude: that.data.latitude,
        picturepaths: that.data.imgUrls
      },
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: '上传成功',
        })
        wx.showModal({
          title: '提交完成提醒',
          content: '感谢您的贡献，信息核实后我们会通过短信通知您',
          showCancel:false,
          success:res=>{
            if(res.confirm){
              wx.navigateBack({
                delta:1
              })
            }
          }
        })
      },
      fail: err => {
        consoel.log(err)
      }
    })
  },
  //提交
  finishReport(e) {
    var that = this;
    wx.showModal({
      title: '确认提交提醒',
      content: '我们会对您的提交进行核查，请保证信息真实',
      success:res=>{
        if(res.cancel){
          return;
        }else{
          console.log('确认提交')
          that.setData({
            formInfo: e
          })
          var date = new Date();
          //年
          var Y = date.getFullYear();
          //月
          var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
          //日
          var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
          //时
          var h = date.getHours();
          //分
          var m = date.getMinutes();
          //秒
          var s = date.getSeconds();
          var path = 'daquan/uploadImg/' + Y + M + D + h + m + s; //为照片命名
          wx.showLoading({
            title: '上传中。。。',
          })
          if (that.data.imgpaths.length != 0) {
            that.uploadimg(path, 0);
          } else {
            that.uploadInfo();
          }
        }
      }
    })
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      imgUrls:[]
    })
    qqmapsdk = new QQMapWX({
      key: 'GBQBZ-EYTW3-66E3Z-3H4U3-GOXV6-SYFLM' //这里自己的secret秘钥进行填充
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})